<template>
  <h2 style="font-size: 1.2rem" class="mb-2">
    {{ $t("账户信息") }}
  </h2>
  <el-card class="mb-4">
    <div class="flex justify-between">
      <div>
        <div class="mb-2">{{ $t("余额") }}</div>
        <p class="mb-2 text-2xl font-semibold">
          {{ state.cardInfo.symbol }} {{ state.cardInfo.total_available }}
        </p>
        <div class="mb-2">{{ $t("卡号") }}</div>
        <p class="flex items-center justify-center text-2xl font-semibold">
          {{ state.cardInfo.bank_card_no || "--" }}
          <el-icon
            class="ml-3 cursor-pointer hideIcon"
            @click="lookCardNo(isHide)"
            v-if="state.cardInfo.bank_card_no"
          >
            <View v-if="!isHide" />
            <Hide v-else />
          </el-icon>
        </p>
      </div>
      <div class="mt-8">
        <el-button
          :plain="true"
          size="large"
          type="danger"
          class="custom-button plainButton"
          @click="receive"
          >{{ $t("收款") }}</el-button
        >
        <el-button
          :plain="true"
          size="large"
          type="danger"
          :icon="Switch"
          @click="pay"
          class="plainButton"
          >{{ $t("VA-付款") }}</el-button
        >
      </div>
    </div>
  </el-card>
  <div class="flex justify-between">
    <h2 style="font-size: 1.2rem" class="mb-2">
      {{ $t("每月流水") }}
    </h2>
    <el-date-picker
      style="width: 15%"
      v-model="state.selectedMonth"
      type="month"
      :placeholder="$t('选择日期')"
      @change="selectDate"
    />
  </div>
  <el-card class="mb-4">
    <ul
      class="flex flex-wrap justify-start recordList grow"
      v-if="visibleItems.length"
    >
      <li v-for="item in visibleItems" :key="item.date">
        <p class="mb-2 text-[#958f8f]">
          {{ item.month < 10 ? "0" + item.month : item.month }}-{{
            item.day < 10 ? "0" + item.day : item.day
          }}
        </p>
        <p>{{ item.sg }} {{ item.amount }} {{ item.currency }}</p>
      </li>
      <!-- 显示折叠按钮 -->
      <div v-if="collapsedItems.length > 0" class="pt-6 ml-20">
        <el-icon
          @click="toggleCollapse"
          v-if="isCollapseNeeded"
          class="cursor-pointer"
        >
          <ArrowDownBold v-if="state.isCollapsed" />
          <ArrowUpBold v-else />
        </el-icon>
      </div>
    </ul>
    <div class="flex items-center justify-center" v-else>
      <p>暂未数据</p>
    </div>
    <!-- 显示折叠后的列表项 -->
    <transition name="fade">
      <ul
        v-show="!state.isCollapsed && isCollapseNeeded"
        class="flex flex-wrap justify-start recordList grow"
      >
        <li v-for="(item, index) in collapsedItems" :key="index">
          <p class="mb-2 text-[#958f8f]">
            {{ item.month < 10 ? "0" + item.month : item.month }}-{{
              item.day < 10 ? "0" + item.day : item.day
            }}
          </p>
          <p>{{ item.sg }} {{ item.amount }} {{ item.currency }}</p>
        </li>
      </ul>
    </transition>
  </el-card>
  <h2 style="font-size: 1.2rem" class="mb-2">
    {{ $t("交易明细") }}
  </h2>
  <el-card>
    <el-table :data="state.tableList" v-loading="loading">
      <el-table-column prop="trade_type" :label="$t('VA-类型')" align="center">
        <template #default="scope">
          <span v-if="scope.row.trade_type === 0">{{ $t("充值") }}</span>
          <span v-if="scope.row.trade_type === 1">{{ $t("收款") }}</span>
          <span v-if="scope.row.trade_type === 2">{{ $t("VA-付款") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="create_time"
        :formatter="formatterTime"
        :label="$t('VA-时间')"
      />
      <el-table-column align="center" :label="$t('VA-金额')">
        <template #default="scope">
          {{ scope.row.sg }} {{ numberToCurrencyNo(scope.row.amount) }}
          {{ scope.row.currency }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" align="center" :label="$t('VA-操作')">
        <template #default="scope">
          <el-button
            round
            icon="MoreFilled"
            class="cursor-pointer"
            @click="showCurrentDetail(scope.row)"
            >{{ $t("查看") }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="flex justify-center mt-5">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageable.total"
        :default-page-size="pageable.pageSize"
        :default-current-page="pageable.pageNum"
        :page-sizes="[10, 25, 50, 100]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </el-card>
  <OrderDetail
    :isShowOrderDetail="isShowOrderDetail"
    :orderNo="currentOrderNo"
    :tradeType="tradeType"
    @close="
      () => {
        currentOrderNo = '';
        isShowOrderDetail = false;
      }
    "
  />
  <Payment
    :isShowPayment="isShowPayment"
    :cardInfo="state.cardInfo"
    :currentUserId="currentUserId"
    @close="
      () => {
        isShowPayment = false;
      }
    "
  />
  <Receive
    :isShowReceive="isShowReceive"
    @close="
      () => {
        isShowReceive = false;
      }
    "
  />
  <el-dialog v-model="dialogVisible" width="30%" @close="payPass = ''">
    <el-input
      v-model="payPass"
      :placeholder="$t('请输入支付密码')"
      type="password"
      show-password
    ></el-input>
    <div class="flex justify-center w-full mt-4">
      <el-button type="danger" @click="lookCard" class="w-40">{{
        $t("确定")
      }}</el-button>
    </div>
  </el-dialog>
</template>
<script setup>
import { Switch, ArrowDownBold, ArrowUpBold } from "@element-plus/icons-vue";
import {
  computed,
  onBeforeUnmount,
  onMounted,
  onUnmounted,
  reactive,
  ref,
} from "vue";
import { numberToCurrencyNo, formatterTime } from "@/utils/utils";
import {
  GetVaBalance,
  GetVaBankAccount,
  GetVaTransaction,
  GetVaStatisticsMonth,
} from "@/api/VAAccount";
import OrderDetail from "./components/orderDetail.vue";
import Payment from "./components/payment/index.vue";
import Receive from "./components/receive/index.vue";
import { ElMessage } from "element-plus";
import { useRouter, useRoute } from "vue-router";
const route = useRoute();

const state = reactive({
  recordList: [],
  tableList: [],
  isCollapsed: true,
  collapseThreshold: 4, // 折叠阈值
  cardInfo: {},
  selectedMonth: "",
});

const selectDate = (val) => {
  getYearAndMonth(val);
};

const isHide = ref(true);
const cardNoHide = ref("");

// 分页
const pageable = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0,
});

const loading = ref(false);

const visibleItems = computed(() => {
  return state.recordList.slice(0, state.collapseThreshold); // 前五个可见项
});

const collapsedItems = computed(() => {
  return state.recordList.slice(state.collapseThreshold); // 折叠后的项
});

const isCollapseNeeded = computed(() => {
  return state.recordList.length > state.collapseThreshold; // 是否需要折叠
});

const toggleCollapse = () => {
  state.isCollapsed = !state.isCollapsed; // 切换折叠状态
};

// 获取资产余额
const getVaBalance = async () => {
  try {
    const data = await GetVaBalance();
    state.cardInfo = data;
    cardNoHide.value = data.bank_card_no;
  } catch {}
};

const payPass = ref("");

const lookCard = async () => {
  if (payPass) {
    try {
      const { bank_card_no } = await GetVaBankAccount({
        password: payPass.value,
      });
      state.cardInfo.bank_card_no = bank_card_no || "";
      isHide.value = false;
      dialogVisible.value = false;
      payPass.value = "";
      ElMessage.success("ok");
    } catch {}
  } else {
    ElMessage.error(t("请输入支付密码"));
  }
};

const dialogVisible = ref(false);

// 查看卡号
const lookCardNo = async (isShow) => {
  if (isShow) {
    dialogVisible.value = true;
  } else {
    state.cardInfo.bank_card_no = cardNoHide.value;
    isHide.value = true;
  }
};

const params = () => {
  return {
    page: pageable.pageNum,
    pagesize: pageable.pageSize,
  };
};

// 交易明细
const getVaTransaction = async () => {
  try {
    loading.value = true;
    const { list, page } = await GetVaTransaction(params());
    state.tableList = list || [];
    pageable.total = page.total_count || 0;
    loading.value = false;
  } catch {
    loading.value = false;
  }
};

const handleCurrentChange = async (number) => {
  pageable.pageNum = number;
  await getVaTransaction();
};
// 条数
const handleSizeChange = async (number) => {
  pageable.pageSize = number;
  await getVaTransaction();
};

const getVaStatisticsMonth = async (params) => {
  const data = {
    ...params,
    page: 1,
    pageSize: 9999,
  };
  try {
    const { list } = await GetVaStatisticsMonth(data);
    state.recordList = list || [];
  } catch {}
};

// 展示详情
const isShowOrderDetail = ref(false);
const currentOrderNo = ref("");
const tradeType = ref();

// 查看
const showCurrentDetail = (row) => {
  isShowOrderDetail.value = true;
  currentOrderNo.value = row.order_no;
  tradeType.value = row.trade_type;
};

const getYearAndMonth = (date) => {
  let currentDate = "";
  if (date) {
    currentDate = new Date(date);
  } else {
    currentDate = new Date();
  }
  // 使用 Date 对象的方法获取当前年份和月份
  const currentYear = currentDate.getFullYear();
  const currentMonth = currentDate.getMonth() + 1; // 月份从 0 开始，所以要加 1
  state.selectedMonth = new Date(currentYear, currentMonth - 1, 1);
  const params = {
    year: currentYear,
    month: currentMonth,
  };
  getVaStatisticsMonth(params);
};

const isShowPayment = ref(false);
const isShowReceive = ref(false);
const currentUserId = ref();

const pay = () => {
  isShowPayment.value = true;
};

const receive = () => {
  isShowReceive.value = true;
};

if (history.state.isAddCustomer) {
  isShowPayment.value = true;
  currentUserId.value = history.state.id;
  clearState();
}

onMounted(() => {
  getVaBalance();
  getVaTransaction();
  getYearAndMonth();
});
// 清除state参数的函数
function clearState() {
  history.state.isAddCustomer = null;
}
</script>
<style lang="scss" scoped>
.custom-button {
  background-image: url("@/assets/images/erweima.png");
  background-repeat: no-repeat;
  background-size: auto 60%; /* 图片宽度自适应，高度占据按钮的整个高度 */
  background-position: 20% 56%;
  padding-left: 50px; /* 增加左边内边距，让文字不会和图片重叠 */
  color: #fff; /* 文字颜色可以根据需要调整 */
}
.recordList {
  li {
    width: 20%;
    padding: 10px;
    height: 80px;
    border: 1px solid #ccc;
    border-radius: 5px;
    margin-bottom: 2%;
  }
  li:not(:last-child) {
    margin-right: 2%;
  }
}
.hideIcon {
  color: #e54c5f !important;
}
</style>
